package com.freesun.shop.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.freesun.shop.entity.Basket;
import com.freesun.shop.entity.Prod;
import com.freesun.shop.entity.Sku;
import com.freesun.shop.mapper.BasketMapper;
import com.freesun.shop.service.BasketService;
import com.freesun.shop.service.ProdService;
import com.freesun.shop.service.SkuService;
import com.freesun.shop.vo.ShopCartItem;
import org.apache.dubbo.config.annotation.Reference;
import org.apache.dubbo.config.annotation.Service;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 购物车 服务实现类
 * </p>
 *
 * @author zf
 * @since 2019-11-13
 */
@Service
public class BasketServiceImpl extends ServiceImpl<BasketMapper, Basket> implements BasketService {
    private static final Logger logger = LoggerFactory.getLogger(BasketServiceImpl.class);

    @Reference(check = false)
    private ProdService prodService;

    @Reference(check = false)
    private SkuService skuService;

    @Override
    public List<ShopCartItem> findByUser(String userId) {
        logger.info("查询当前用户{}的购物车数据",userId);
        List<Basket> baskets = this.baseMapper.selectList(new LambdaQueryWrapper<Basket>()
                .eq(Basket::getUserId, userId));
        if(baskets==null) {
            return null ;
        }
        List<ShopCartItem> shopCartItems = getShopCartItems(baskets);

        return shopCartItems;
    }

    private List<ShopCartItem> getShopCartItems(List<Basket> baskets) {
        List<ShopCartItem> shopCartItems = new ArrayList<ShopCartItem>(baskets.size());
        for (Basket basket : baskets) {
            ShopCartItem shopCartItem = basket2shopCartItem(basket);
            shopCartItems.add(shopCartItem);
        }
        return shopCartItems;
    }

    @Override
    public List<ShopCartItem> findByBasketIds(List<Long> asList) {
        logger.info("查询购物车{}的数据",asList);
        List<Basket> baskets = this.baseMapper.selectList(new LambdaQueryWrapper<Basket>()
                .in(Basket::getBasketId, asList));
        if(baskets==null) {
            return null ;
        }
        List<ShopCartItem> shopCartItems = getShopCartItems(baskets);

        return shopCartItems;

    }

    private ShopCartItem basket2shopCartItem(Basket basket) {
        ShopCartItem shopCartItem = new ShopCartItem();
        shopCartItem.setBasketId(basket.getBasketId());
        shopCartItem.setChecked(true);
        shopCartItem.setSkuId(basket.getSkuId());
        shopCartItem.setProdId(basket.getProdId());
        shopCartItem.setProdCount(basket.getBasketCount());
        Prod prod = prodService.getSimpleProd(basket.getProdId());
        shopCartItem.setProdName(prod.getProdName()); // 商品的名称
        Sku sku = skuService.getById(basket.getSkuId());
        shopCartItem.setPic(StringUtils.hasText(sku.getPic())?sku.getPic():prod.getPic());
        shopCartItem.setPrice(sku.getPrice()==null?prod.getPrice():sku.getPrice()); // 商品的价格(sku的价格还是商品的价格)
        shopCartItem.setSkuName(sku.getSkuName()); // sku的名称
        return shopCartItem;
    }

    @Override
    public Integer getProdCountByUser(String userId) {
        Assert.notNull(userId,"用户的ID不能为Null");
        logger.info("开始查询用户:{}的购物车数量",userId);
        QueryWrapper<Basket> queryWrapper=new QueryWrapper<>();
        queryWrapper.select(" SUM(basket_count) ");
        queryWrapper.eq("user_id", userId);
        List<Object> objects = this.baseMapper.selectObjs(queryWrapper);
        if(null==objects||objects.isEmpty()){
            return 0;
        }
        return Integer.valueOf(objects.get(0).toString());
    }

    @Override
    public void changeItem(Basket basket) {

        if(
                basket==null||
                basket.getBasketCount()==null||
                basket.getProdId()==null||
                basket.getSkuId()==null
        ){
            throw new RuntimeException("添加到购物车的数据有误");
        }
       //通过userID+skuID+shopid表示商品的唯一性
        Basket basketDb = this.baseMapper.selectOne(new LambdaQueryWrapper<Basket>()
                .eq(Basket::getUserId, basket.getUserId())
                .eq(Basket::getSkuId, basket.getSkuId()));
        if (basketDb != null) { //之前有该购物车记录,需要修改数量
            Integer currentBasketCount = basket.getBasketCount();
            Integer basketCountDb = basketDb.getBasketCount();
            Integer num = basketCountDb + currentBasketCount ;
            if(num<=0) {
                this.baseMapper.deleteById(basketDb.getBasketId());
            }else {
                Basket setBasketCount = basketDb.setBasketCount(num);
                this.baseMapper.updateById(setBasketCount);
            }
        }else {
            //之前没有该条目，添加新的记录
            basket.setBasketDate(LocalDateTime.now());
            this.baseMapper.insert(basket);
        }
    }
    private static final DecimalFormat PRICE_PATTERN = new DecimalFormat("0.00");
    @Override
    public BigDecimal getTotalPay(List<Long> ids) {
        Assert.notNull(ids,"购物车条目价格不能为Null");
        List<Basket> baskets = this.baseMapper.selectBatchIds(ids);
        if(baskets==null||baskets.isEmpty()) {
            return new BigDecimal("0.00");
        }
        double totalMoney = 0.00 ;
        for (Basket basket : baskets) {
            Long skuId = basket.getSkuId();
            double itemPrice = 0.00 ;
            Sku sku = skuService.getById(skuId);
            if(sku.getPrice()==null) {
                Prod prod = prodService.getSimpleProd(basket.getProdId());
                itemPrice = prod.getPrice().doubleValue();
            }else {
                itemPrice = sku.getPrice().doubleValue();
            }
            totalMoney += (basket.getBasketCount().intValue()) * itemPrice;

        }
        // 保留2 位数子
        return new BigDecimal(PRICE_PATTERN.format(totalMoney));

    }

    /**
     * 清空购物车条目
     */
    @Override
    public void clearItem(List<Long> basketIds) {
        this.baseMapper.deleteBatchIds(basketIds);
    }
}



